import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:window_manager/window_manager.dart';
import 'home_page.dart';
import 'unified_project_page.dart';
import 'build_config_page.dart';
import 'ai_build_suggestions_page.dart';
import 'pages/build_monitor_page.dart';
import 'help_page.dart';
import 'about_page.dart';
import 'models/unified_config.dart';

// ================ 主函数 ================
void main() async {
  // 确保Flutter绑定初始化
  WidgetsFlutterBinding.ensureInitialized();

  // 初始化窗口配置
  await WindowConfig.initWindow();

  runApp(const NuitkaBuilderApp());
}

// ================ 应用类 ================
class NuitkaBuilderApp extends StatefulWidget {
  const NuitkaBuilderApp({super.key});

  @override
  State<NuitkaBuilderApp> createState() => _NuitkaBuilderAppState();
}

class _NuitkaBuilderAppState extends State<NuitkaBuilderApp> {
  bool _isDarkMode = false;
  ThemeColor _themeColor = ThemeColor.blue;

  void updateTheme({bool? isDarkMode, ThemeColor? themeColor}) {
    setState(() {
      if (isDarkMode != null) _isDarkMode = isDarkMode;
      if (themeColor != null) _themeColor = themeColor;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Python Nuitka构建工具',
      debugShowCheckedModeBanner: false,
      theme: AppTheme.getLightTheme(_themeColor),
      darkTheme: AppTheme.getDarkTheme(_themeColor),
      themeMode: _isDarkMode ? ThemeMode.dark : ThemeMode.light,
      home: MainPage(
        isDarkMode: _isDarkMode,
        themeColor: _themeColor,
        onThemeChanged: updateTheme,
      ),
    );
  }
}

// ================ 主题颜色枚举 ================
enum ThemeColor { blue, green, purple, orange, red, teal }

// 主题颜色扩展
extension ThemeColorExtension on ThemeColor {
  String get name {
    switch (this) {
      case ThemeColor.blue:
        return '蓝色';
      case ThemeColor.green:
        return '绿色';
      case ThemeColor.purple:
        return '紫色';
      case ThemeColor.orange:
        return '橙色';
      case ThemeColor.red:
        return '红色';
      case ThemeColor.teal:
        return '青色';
    }
  }

  Color get primaryColor {
    switch (this) {
      case ThemeColor.blue:
        return const Color(0xFF0D47A1);
      case ThemeColor.green:
        return const Color(0xFF2E7D32);
      case ThemeColor.purple:
        return const Color(0xFF6A1B9A);
      case ThemeColor.orange:
        return const Color(0xFFE65100);
      case ThemeColor.red:
        return const Color(0xFFC62828);
      case ThemeColor.teal:
        return const Color(0xFF00695C);
    }
  }

  Color get secondaryColor {
    switch (this) {
      case ThemeColor.blue:
        return const Color(0xFF1976D2);
      case ThemeColor.green:
        return const Color(0xFF388E3C);
      case ThemeColor.purple:
        return const Color(0xFF7B1FA2);
      case ThemeColor.orange:
        return const Color(0xFFFF6F00);
      case ThemeColor.red:
        return const Color(0xFFD32F2F);
      case ThemeColor.teal:
        return const Color(0xFF00796B);
    }
  }

  IconData get icon {
    switch (this) {
      case ThemeColor.blue:
        return Icons.build;
      case ThemeColor.green:
        return Icons.forest;
      case ThemeColor.purple:
        return Icons.palette;
      case ThemeColor.orange:
        return Icons.emoji_food_beverage;
      case ThemeColor.red:
        return Icons.favorite;
      case ThemeColor.teal:
        return Icons.waves;
    }
  }
}

// ================ 导航项枚举 ================
enum NavigationItem {
  home,
  projectSetup,
  buildConfig,
  aiSuggestions,
  buildMonitor,
  helpDocs,
  about,
}

extension NavigationItemExtension on NavigationItem {
  String get title {
    switch (this) {
      case NavigationItem.home:
        return '主页';
      case NavigationItem.projectSetup:
        return '项目设置';
      case NavigationItem.buildConfig:
        return '构建配置';
      case NavigationItem.aiSuggestions:
        return 'AI构建建议';
      case NavigationItem.buildMonitor:
        return '构建监控';
      case NavigationItem.helpDocs:
        return '帮助文档';
      case NavigationItem.about:
        return '关于';
    }
  }

  String get subtitle {
    switch (this) {
      case NavigationItem.home:
        return '欢迎使用Nuitka构建工具';
      case NavigationItem.projectSetup:
        return '选择Python文件和基本设置';
      case NavigationItem.buildConfig:
        return '配置Nuitka参数和依赖';
      case NavigationItem.aiSuggestions:
        return '智能分析Python文件并推荐最佳配置';
      case NavigationItem.buildMonitor:
        return '监控构建进度和日志';
      case NavigationItem.helpDocs:
        return '查看使用说明和文档';
      case NavigationItem.about:
        return '版本信息和联系方式';
    }
  }

  IconData get icon {
    switch (this) {
      case NavigationItem.home:
        return Icons.home;
      case NavigationItem.projectSetup:
        return Icons.folder_open;
      case NavigationItem.buildConfig:
        return Icons.build;
      case NavigationItem.aiSuggestions:
        return Icons.psychology;
      case NavigationItem.buildMonitor:
        return Icons.monitor;
      case NavigationItem.helpDocs:
        return Icons.help_outline;
      case NavigationItem.about:
        return Icons.info_outline;
    }
  }
}

// ================ 窗口配置 ================
class WindowConfig {
  static const Size defaultSize = Size(1400, 900);
  static const Size minSize = Size(1000, 700);

  static Future<void> initWindow() async {
    await windowManager.ensureInitialized();

    WindowOptions windowOptions = const WindowOptions(
      size: defaultSize,
      minimumSize: minSize,
      center: true,
      backgroundColor: Colors.transparent,
      skipTaskbar: false,
      titleBarStyle: TitleBarStyle.hidden,
    );

    await windowManager.waitUntilReadyToShow(windowOptions, () async {
      await windowManager.show();
      await windowManager.focus();
    });
  }

  static Future<void> minimize() async {
    try {
      await windowManager.minimize();
    } catch (e) {
      debugPrint('Failed to minimize window: $e');
    }
  }

  static Future<void> toggleMaximize() async {
    try {
      final isMaximized = await windowManager.isMaximized();
      if (isMaximized) {
        await windowManager.unmaximize();
      } else {
        await windowManager.maximize();
      }
    } catch (e) {
      debugPrint('Failed to toggle maximize window: $e');
    }
  }

  static Future<void> close() async {
    try {
      await windowManager.close();
    } catch (e) {
      debugPrint('Failed to close window: $e');
    }
  }
}

// ================ 主题配置 ================
class AppTheme {
  // 边框和阴影
  static const double borderRadius = 16.0;
  static const double borderRadiusSmall = 8.0;
  static const double borderRadiusLarge = 24.0;
  static const double elevation = 2.0;
  static const double elevationHigh = 8.0;

  // 间距
  static const double spacingTiny = 4.0;
  static const double spacingSmall = 8.0;
  static const double spacingMedium = 16.0;
  static const double spacingLarge = 24.0;
  static const double spacingXLarge = 32.0;
  static const double spacingXXLarge = 48.0;

  // 动画时长
  static const Duration animationDuration = Duration(milliseconds: 200);
  static const Duration animationDurationLong = Duration(milliseconds: 300);

  // 获取亮色主题
  static ThemeData getLightTheme(ThemeColor themeColor) {
    final primaryColor = themeColor.primaryColor;
    final secondaryColor = themeColor.secondaryColor;
    const errorColor = Color(0xFFD32F2F);
    const backgroundColor = Color(0xFFFCFCFC);
    const surfaceColor = Colors.white;

    return ThemeData(
      colorScheme: ColorScheme.fromSeed(
        seedColor: primaryColor,
        primary: primaryColor,
        secondary: secondaryColor,
        error: errorColor,
        brightness: Brightness.light,
        surface: surfaceColor,
        background: backgroundColor,
        onPrimary: Colors.white,
        onSecondary: Colors.white,
        onSurface: const Color(0xFF1C1B1F),
        onBackground: const Color(0xFF1C1B1F),
      ),
      fontFamilyFallback: const ['Segoe UI', 'Microsoft YaHei', 'sans-serif'],
      useMaterial3: true,
      brightness: Brightness.light,
      scaffoldBackgroundColor: backgroundColor,
    );
  }

  // 获取暗色主题
  static ThemeData getDarkTheme(ThemeColor themeColor) {
    final primaryColor = themeColor.secondaryColor;
    final secondaryColor = themeColor.primaryColor;
    const errorColor = Color(0xFFFFB4AB);
    const backgroundColor = Color(0xFF101014);
    const surfaceColor = Color(0xFF1C1B1F);

    return ThemeData(
      colorScheme: ColorScheme.fromSeed(
        seedColor: primaryColor,
        primary: primaryColor,
        secondary: secondaryColor,
        error: errorColor,
        brightness: Brightness.dark,
        surface: surfaceColor,
        background: backgroundColor,
        onPrimary: const Color(0xFF000000),
        onSecondary: const Color(0xFF000000),
        onSurface: const Color(0xFFE6E1E5),
        onBackground: const Color(0xFFE6E1E5),
      ),
      fontFamilyFallback: const ['Segoe UI', 'Microsoft YaHei', 'sans-serif'],
      useMaterial3: true,
      brightness: Brightness.dark,
      scaffoldBackgroundColor: backgroundColor,
    );
  }
}

// ================ 自定义标题栏 ================
class CustomTitleBar extends StatefulWidget implements PreferredSizeWidget {
  final String title;
  final List<Widget>? actions;
  final Color? backgroundColor;
  final Color? foregroundColor;
  final double height;

  const CustomTitleBar({
    super.key,
    required this.title,
    this.actions,
    this.backgroundColor,
    this.foregroundColor,
    this.height = 45.0,
  });

  @override
  State<CustomTitleBar> createState() => _CustomTitleBarState();

  @override
  Size get preferredSize => Size.fromHeight(height);
}

class _CustomTitleBarState extends State<CustomTitleBar> with WindowListener {
  bool _isMaximized = false;

  @override
  void initState() {
    super.initState();
    windowManager.addListener(this);
    _init();
  }

  @override
  void dispose() {
    windowManager.removeListener(this);
    super.dispose();
  }

  void _init() async {
    _isMaximized = await windowManager.isMaximized();
    setState(() {});
  }

  @override
  void onWindowMaximize() {
    setState(() {
      _isMaximized = true;
    });
  }

  @override
  void onWindowUnmaximize() {
    setState(() {
      _isMaximized = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final isDark = theme.brightness == Brightness.dark;
    final backgroundColor =
        widget.backgroundColor ??
        (isDark ? theme.colorScheme.surface : Colors.white);
    final foregroundColor =
        widget.foregroundColor ??
        (isDark ? theme.colorScheme.onSurface : theme.colorScheme.onSurface);

    return Container(
      height: widget.height,
      decoration: BoxDecoration(
        color: backgroundColor,
        border: Border(
          bottom: BorderSide(
            color: theme.dividerColor.withOpacity(0.12),
            width: 1,
          ),
        ),
      ),
      child: Row(
        children: [
          // 应用图标和标题
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16.0),
            child: Row(
              children: [
                Icon(Icons.build_circle, size: 24, color: foregroundColor),
                const SizedBox(width: 12),
                Text(
                  widget.title,
                  style: TextStyle(
                    color: foregroundColor,
                    fontWeight: FontWeight.w600,
                    fontSize: 16,
                  ),
                ),
              ],
            ),
          ),

          // 可拖动区域
          Expanded(
            child: GestureDetector(
              onDoubleTap: () => WindowConfig.toggleMaximize(),
              child: DragToMoveArea(child: Container()),
            ),
          ),

          // 自定义操作按钮
          if (widget.actions != null) ...widget.actions!,

          // 窗口控制按钮
          _buildWindowButton(
            icon: Icons.minimize,
            onPressed: WindowConfig.minimize,
            foregroundColor: foregroundColor,
            tooltip: '最小化',
          ),
          _buildWindowButton(
            icon: _isMaximized ? Icons.crop_square : Icons.crop_7_5,
            onPressed: WindowConfig.toggleMaximize,
            foregroundColor: foregroundColor,
            tooltip: _isMaximized ? '还原' : '最大化',
          ),
          _buildWindowButton(
            icon: Icons.close,
            onPressed: WindowConfig.close,
            foregroundColor: foregroundColor,
            hoverColor: Colors.red,
            tooltip: '关闭',
          ),
        ],
      ),
    );
  }

  Widget _buildWindowButton({
    required IconData icon,
    required VoidCallback onPressed,
    required Color foregroundColor,
    Color? hoverColor,
    String? tooltip,
  }) {
    return Tooltip(
      message: tooltip ?? '',
      child: SizedBox(
        width: 46,
        height: double.infinity,
        child: Material(
          color: Colors.transparent,
          child: InkWell(
            onTap: onPressed,
            hoverColor: hoverColor ?? foregroundColor.withOpacity(0.08),
            splashColor: foregroundColor.withOpacity(0.12),
            borderRadius: BorderRadius.circular(4),
            child: Icon(icon, size: 16, color: foregroundColor),
          ),
        ),
      ),
    );
  }
}

// ================ 主页面 ================
class MainPage extends StatefulWidget {
  final bool isDarkMode;
  final ThemeColor themeColor;
  final Function({bool? isDarkMode, ThemeColor? themeColor}) onThemeChanged;

  const MainPage({
    super.key,
    required this.isDarkMode,
    required this.themeColor,
    required this.onThemeChanged,
  });

  @override
  State<MainPage> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  NavigationItem _selectedItem = NavigationItem.home;
  int _selectedIndex = 0;
  bool _showThemeSelector = false;

  void _selectNavigationItem(NavigationItem item) {
    setState(() {
      _selectedItem = item;
    });
  }

  void _toggleTheme() {
    widget.onThemeChanged(isDarkMode: !widget.isDarkMode);
  }

  void _toggleThemeSelector() {
    setState(() {
      _showThemeSelector = !_showThemeSelector;
    });
  }

  void _selectThemeColor(ThemeColor color) {
    widget.onThemeChanged(themeColor: color);
    setState(() {
      _showThemeSelector = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);

    return Scaffold(
      appBar: CustomTitleBar(
        title: 'Python Nuitka构建工具 v1.0.0.0',
        backgroundColor: theme.colorScheme.primary,
        foregroundColor: Colors.white,
        actions: [
          // 主题颜色选择按钮
          IconButton(
            icon: Icon(widget.themeColor.icon, color: Colors.white),
            tooltip: '选择主题颜色',
            onPressed: _toggleThemeSelector,
          ),
          // 亮暗主题切换按钮
          IconButton(
            icon: Icon(
              widget.isDarkMode ? Icons.light_mode : Icons.dark_mode,
              color: Colors.white,
            ),
            tooltip: '切换亮暗主题',
            onPressed: _toggleTheme,
          ),
        ],
      ),
      body: Stack(
        children: [
          Row(
            children: [
              // 侧边导航栏
              _buildSideNavigation(theme),
              // 主内容区域
              Expanded(child: _buildMainContent(theme)),
            ],
          ),
          if (_showThemeSelector) _buildThemeSelector(theme),
        ],
      ),
    );
  }

  Widget _buildSideNavigation(ThemeData theme) {
    return AnimatedContainer(
      duration: AppTheme.animationDuration,
      width: 280,
      decoration: BoxDecoration(
        color: theme.colorScheme.surface,
        border: Border(
          right: BorderSide(
            color: theme.dividerColor.withOpacity(0.12),
            width: 1,
          ),
        ),
      ),
      child: Column(
        children: [
          // 导航标题
          Container(
            padding: const EdgeInsets.all(AppTheme.spacingLarge),
            child: Row(
              children: [
                Icon(
                  Icons.build_circle,
                  size: 32,
                  color: theme.colorScheme.primary,
                ),
                const SizedBox(width: AppTheme.spacingMedium),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'Nuitka构建工具',
                        style: theme.textTheme.titleLarge?.copyWith(
                          color: theme.colorScheme.primary,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      Text(
                        'Python编译助手',
                        style: theme.textTheme.bodySmall?.copyWith(
                          color: theme.colorScheme.onSurface.withOpacity(0.6),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),

          const Divider(height: 1),

          // 导航菜单
          Expanded(
            child: ListView(
              padding: const EdgeInsets.symmetric(
                vertical: AppTheme.spacingMedium,
              ),
              children: NavigationItem.values.map((item) {
                final isSelected = item == _selectedItem;
                return Container(
                  margin: const EdgeInsets.symmetric(
                    horizontal: AppTheme.spacingMedium,
                    vertical: AppTheme.spacingTiny,
                  ),
                  child: AnimatedContainer(
                    duration: AppTheme.animationDuration,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(
                        AppTheme.borderRadius,
                      ),
                      color: isSelected
                          ? theme.colorScheme.primaryContainer
                          : Colors.transparent,
                    ),
                    child: Material(
                      color: Colors.transparent,
                      child: InkWell(
                        borderRadius: BorderRadius.circular(
                          AppTheme.borderRadius,
                        ),
                        onTap: () => _selectNavigationItem(item),
                        child: Padding(
                          padding: const EdgeInsets.symmetric(
                            horizontal: AppTheme.spacingMedium,
                            vertical: AppTheme.spacingMedium,
                          ),
                          child: Row(
                            children: [
                              AnimatedContainer(
                                duration: AppTheme.animationDuration,
                                padding: const EdgeInsets.all(8),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(8),
                                  color: isSelected
                                      ? theme.colorScheme.primary
                                      : Colors.transparent,
                                ),
                                child: Icon(
                                  item.icon,
                                  size: 20,
                                  color: isSelected
                                      ? theme.colorScheme.onPrimary
                                      : theme.colorScheme.primary.withOpacity(
                                          0.8,
                                        ),
                                ),
                              ),
                              const SizedBox(width: AppTheme.spacingMedium),
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    AnimatedDefaultTextStyle(
                                      duration: AppTheme.animationDuration,
                                      style: TextStyle(
                                        color: isSelected
                                            ? theme
                                                  .colorScheme
                                                  .onPrimaryContainer
                                            : theme.colorScheme.onSurface,
                                        fontWeight: isSelected
                                            ? FontWeight.w600
                                            : FontWeight.w500,
                                        fontSize: 16,
                                        letterSpacing: 0.15,
                                      ),
                                      child: Text(item.title),
                                    ),
                                    const SizedBox(height: 2),
                                    AnimatedDefaultTextStyle(
                                      duration: AppTheme.animationDuration,
                                      style: TextStyle(
                                        color: isSelected
                                            ? theme
                                                  .colorScheme
                                                  .onPrimaryContainer
                                                  .withOpacity(0.7)
                                            : theme.colorScheme.onSurface
                                                  .withOpacity(0.6),
                                        fontWeight: FontWeight.w400,
                                        fontSize: 12,
                                        letterSpacing: 0.4,
                                      ),
                                      child: Text(item.subtitle),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
                );
              }).toList(),
            ),
          ),

          // 底部状态信息
          Container(
            padding: const EdgeInsets.all(AppTheme.spacingMedium),
            decoration: BoxDecoration(
              border: Border(
                top: BorderSide(
                  color: theme.dividerColor.withOpacity(0.2),
                  width: 1,
                ),
              ),
            ),
            child: Row(
              children: [
                Icon(
                  Icons.info_outline,
                  size: 16,
                  color: theme.colorScheme.onSurface.withOpacity(0.6),
                ),
                const SizedBox(width: AppTheme.spacingSmall),
                Expanded(
                  child: Text(
                    '就绪 - 选择功能开始使用',
                    style: theme.textTheme.bodySmall?.copyWith(
                      color: theme.colorScheme.onSurface.withOpacity(0.6),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildMainContent(ThemeData theme) {
    return AnimatedContainer(
      duration: AppTheme.animationDuration,
      color: theme.colorScheme.background,
      child: AnimatedSwitcher(
        duration: AppTheme.animationDurationLong,
        transitionBuilder: (Widget child, Animation<double> animation) {
          return FadeTransition(
            opacity: animation,
            child: SlideTransition(
              position:
                  Tween<Offset>(
                    begin: const Offset(0.1, 0),
                    end: Offset.zero,
                  ).animate(
                    CurvedAnimation(
                      parent: animation,
                      curve: Curves.easeOutCubic,
                    ),
                  ),
              child: child,
            ),
          );
        },
        child: Container(
          key: ValueKey(
            '${_selectedItem.name}_${widget.isDarkMode ? 'dark' : 'light'}',
          ),
          child: _getContentForSelectedItem(),
        ),
      ),
    );
  }

  Widget _getContentForSelectedItem() {
    switch (_selectedItem) {
      case NavigationItem.home:
        return _buildHomePage();
      case NavigationItem.projectSetup:
        return _buildProjectSetupPage();
      case NavigationItem.buildConfig:
        return _buildBuildConfigPage();
      case NavigationItem.aiSuggestions:
        return _buildAISuggestionsPage();
      case NavigationItem.buildMonitor:
        return _buildBuildMonitorPage();
      case NavigationItem.helpDocs:
        return _buildHelpDocsPage();
      case NavigationItem.about:
        return _buildAboutPage();
    }
  }

  Widget _buildHomePage() {
    return HomePage(
      onNavigate: (index) {
        setState(() {
          // 根据索引切换到对应的导航项
          switch (index) {
            case 0:
              _selectedItem = NavigationItem.home;
              break;
            case 1:
              _selectedItem = NavigationItem.projectSetup;
              break;
            case 2:
              _selectedItem = NavigationItem.buildConfig;
              break;
            case 3:
              _selectedItem = NavigationItem.aiSuggestions;
              break;
            case 4:
              _selectedItem = NavigationItem.buildMonitor;
              break;
            case 5:
              _selectedItem = NavigationItem.helpDocs;
              break;
            case 6:
              _selectedItem = NavigationItem.about;
              break;
            default:
              _selectedItem = NavigationItem.buildConfig;
          }
        });
      },
    );
  }

  Widget _buildProjectSetupPage() {
    return UnifiedProjectPage(isDarkMode: widget.isDarkMode);
  }

  Widget _buildBuildConfigPage() {
    return const BuildConfigPage();
  }

  Widget _buildAISuggestionsPage() {
    return AIBuildSuggestionsPage(
      onNavigateToPage: (pageIndex) {
        setState(() {
          _selectedIndex = int.parse(pageIndex.toString());
          // 根据页面索引切换导航项
          switch (pageIndex) {
            case 0:
              _selectedItem = NavigationItem.home;
              break;
            case 1:
              _selectedItem = NavigationItem.projectSetup;
              break;
            case 2:
              _selectedItem = NavigationItem.buildConfig;
              break;
            case 3:
              _selectedItem = NavigationItem.aiSuggestions;
              break;
            case 4:
              _selectedItem = NavigationItem.buildMonitor;
              break;
            case 5:
              _selectedItem = NavigationItem.helpDocs;
              break;
            case 6:
              _selectedItem = NavigationItem.about;
              break;
          }
        });
      },
    );
  }

  Widget _buildBuildMonitorPage() {
    // 创建一个默认配置，或者从SharedPreferences加载
    return FutureBuilder<UnifiedConfig>(
      future: _loadConfigFromPrefs(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return BuildMonitorPage(config: snapshot.data!);
        } else {
          return BuildMonitorPage(config: UnifiedConfig());
        }
      },
    );
  }

  Future<UnifiedConfig> _loadConfigFromPrefs() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final configJson = prefs.getString('unified_config');
      if (configJson != null) {
        final Map<String, dynamic> configMap = json.decode(configJson);
        return UnifiedConfig.fromJson(configMap);
      }
    } catch (e) {
      print('Error loading config: $e');
    }
    return UnifiedConfig();
  }

  Widget _buildHelpDocsPage() {
    return const HelpPage();
  }

  Widget _buildAboutPage() {
    return const AboutPage();
  }

  Widget _buildThemeSelector(ThemeData theme) {
    return Positioned(
      top: 60,
      right: 16,
      child: AnimatedContainer(
        duration: AppTheme.animationDurationLong,
        child: Card(
          elevation: AppTheme.elevationHigh,
          shadowColor: theme.colorScheme.shadow.withOpacity(0.2),
          surfaceTintColor: theme.colorScheme.surfaceTint,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(AppTheme.borderRadiusLarge),
          ),
          child: Container(
            width: 280,
            padding: const EdgeInsets.all(AppTheme.spacingLarge),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                Row(
                  children: [
                    Icon(
                      Icons.palette_outlined,
                      color: theme.colorScheme.primary,
                      size: 20,
                    ),
                    const SizedBox(width: AppTheme.spacingSmall),
                    Text(
                      '选择主题颜色',
                      style: theme.textTheme.titleMedium?.copyWith(
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: AppTheme.spacingLarge),
                GridView.count(
                  shrinkWrap: true,
                  crossAxisCount: 3,
                  mainAxisSpacing: AppTheme.spacingMedium,
                  crossAxisSpacing: AppTheme.spacingMedium,
                  childAspectRatio: 1,
                  children: ThemeColor.values.map((color) {
                    final isSelected = color == widget.themeColor;
                    return AnimatedContainer(
                      duration: AppTheme.animationDuration,
                      child: Material(
                        color: Colors.transparent,
                        child: InkWell(
                          onTap: () => _selectThemeColor(color),
                          borderRadius: BorderRadius.circular(
                            AppTheme.borderRadius,
                          ),
                          child: AnimatedContainer(
                            duration: AppTheme.animationDuration,
                            decoration: BoxDecoration(
                              color: color.primaryColor,
                              borderRadius: BorderRadius.circular(
                                AppTheme.borderRadius,
                              ),
                              border: isSelected
                                  ? Border.all(
                                      color: theme.colorScheme.outline,
                                      width: 3,
                                    )
                                  : Border.all(
                                      color: theme.colorScheme.outline
                                          .withOpacity(0.2),
                                      width: 1,
                                    ),
                              boxShadow: isSelected
                                  ? [
                                      BoxShadow(
                                        color: color.primaryColor.withOpacity(
                                          0.3,
                                        ),
                                        blurRadius: 12,
                                        spreadRadius: 2,
                                      ),
                                    ]
                                  : [
                                      BoxShadow(
                                        color: Colors.black.withOpacity(0.1),
                                        blurRadius: 4,
                                        offset: const Offset(0, 2),
                                      ),
                                    ],
                            ),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                AnimatedScale(
                                  duration: AppTheme.animationDuration,
                                  scale: isSelected ? 1.2 : 1.0,
                                  child: Icon(
                                    color.icon,
                                    color: Colors.white,
                                    size: 24,
                                  ),
                                ),
                                const SizedBox(height: AppTheme.spacingSmall),
                                Text(
                                  color.name,
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 12,
                                    fontWeight: isSelected
                                        ? FontWeight.w600
                                        : FontWeight.w500,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    );
                  }).toList(),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
